package com.example.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import java.util.Map;

@Configuration
@Slf4j
public class WebSocketConfig implements WebSocketConfigurer {
     
	private final MyWebSocketHandler wsHandler;
     
       /**
         * WebSecoket握手拦截器(执行相关业务逻辑)
         */
	private HandshakeInterceptor handshakeInterceptor = new HandshakeInterceptor() {
		/**
         * 在获取请求或响应之前进行拦截，获取一些请求或响应的数据
         * @param request
         * @param response
         * @param wsHandler
         * @param attributes 如果该方法通过，可以在监听器或controller层拿到这里设置的数据
         * @return 返回false则拦截，返回true则通过
         * @throws Exception
         */
        @Override
        public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
           // 进行业务逻辑处理
            return true; // 返回true
        }

	   /**
         * 在通过请求或响应之后被调用
         * @param request
         * @param response
         * @param wsHandler
         * @param exception
         */
        @Override
        public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

        }
	};
     
    public WebSocketConfig(MyWebSocketHandler wsHandler) {
    	this.wsHandler = wsHandler;
    }
     
    /**
      * websocket拦截器（springsecurity需要配置，因为springsecurity拦截不到websocket）
      * @ServerEndpoint("/websocket") 拦截的是websocket连接的服务
      * @param registry
      */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(wsHandler, "/websocket") // 拦截路径
                .setAllowedOrigins("*")
                .addInterceptors(handshakeInterceptor); // 拦截之后进去的拦截器
    }

    /**
      * 配置ServerEndpointExporter，配置后会自动注册所有“@ServerEndpoint”注解声明的Websocket Endpoint
      * @return
      */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
